<template>
  <div>
    <el-card class="box-card" shadow="always" style="margin:1px;" :body-style="bodyStyle">
      <div slot="header">
        <span>文章分类设置</span>
        <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
      </div>
      <div class="headerOperation">
        <div style="float:left;margin-left:10px;">
          <el-input v-model="searchKey" placeholder="请输入你要查找的内容" style="width:200px;margin-right:10px;" />
          <el-button icon="el-icon-search" type="primary" @click="handleFilter" @keyup.enter.native="handleFilter">筛选</el-button>
        </div>
        <div style="float:right;margin-right:10px;">
          <el-button icon="el-icon-edit" type="primary" @click="handleAdd">添加</el-button>
          <el-button icon="el-icon-refresh" type="primary" @click="handleRefresh">刷新</el-button>
        </div>
      </div>
    </el-card>
    <div>
      <el-table :data="tableList">
        <el-table-column label="Id" prop="id" />
        <el-table-column label="分类名称" prop="categoryName" />
        <el-table-column label="上级分类" prop="parentCategoryName" />
        <el-table-column label="描述" prop="description" />
        <el-table-column label="备注" prop="remarks" />
        <el-table-column
          prop="isActived"
          label="状态"
          width="100"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.isActived === 1 ? 'primary' : 'danger'"
              disable-transitions
            >
              {{ scope.row.isActived === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="300px">
          <template slot-scope="{row,$index}">
            <el-button size="mini" type="warning" @click="handleEnableOrDisable(row,$index)">{{ row.isActived === 1 ? '禁用' : '启用' }}</el-button>
            <el-button size="mini" type="primary" @click="handleEdit(row,$index)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDel(row.id,$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="pageData.pageIndex"
        :page-size="pageData.pageSize"
        :page-sizes="[10,20,30,50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.totalItem"
        @size-change="handlePageSizeChange"
        @current-change="handlePageIndexChange"
      />
      <el-dialog title="分类信息" :visible.sync="dialogFormVisible" @close="handleDialogClose">
        <el-form ref="formDialog" :model="formData">
          <!-- <el-form-item label="id" prop="id" :label-width="lableWidth">
            <el-input v-model="formData.id" class="inputWidth" />
          </el-form-item> -->
          <el-form-item label="分类名称" prop="categoryName" :label-width="lableWidth">
            <el-input v-model="formData.categoryName" class="inputWidth" />
          </el-form-item>
          <el-form-item label="上级分类" prop="parentCategoryId" :label-width="lableWidth">
            <el-select v-model="formData.parentCategoryId" placeholder="请选择" @change="selectChanged">
              <el-option
                v-for="item in selectCategoryList"
                :key="item.id"
                :label="item.categoryName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="描述" prop="description" :label-width="lableWidth">
            <el-input v-model="formData.description" class="inputWidth" />
          </el-form-item>
          <el-form-item label="备注" prop="remarks" :label-width="lableWidth">
            <el-input v-model="formData.remarks" class="inputWidth" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleFormCancel">取 消</el-button>
          <el-button type="primary" @click="handleFormConfirm">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getArticleCategory, addArticleCategory, updateArticleCategory, deleteArticleCategory, updateCategoryStatus, getCategoryForSelect } from '@/api/articleCategory'
export default {
  data() {
    return {
      tableList: [],
      selectCategoryList: [],
      pageData: {
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        totalItem: 0
      },
      searchKey: '',
      dialogFormVisible: false,
      isAddBtnClick: true,
      lableWidth: '20%',
      currentIndex: -1,
      selectRoleList: [],
      // selectedCategory: 0,
      formData: {
        id: 0,
        categoryName: '',
        isActived: 1,
        description: '',
        remarks: '',
        parentCategoryId: '',
        parentCategoryName: ''
      },
      defaultCheckedKeys: [],
      bodyStyle: {
        padding: '0px'
      }
    }
  },
  // 计算属性，获取待编辑角色权限
  computed: {
  },
  created: function() {
    // this.fetchList()
    this.tableList = this.fetchList()
  },
  methods: {
    fetchList: function() {
      this.getArticleCategoryList()
      this.getForSelectList(0)
    },
    handleFilter: function() {
      // console.log(this.searchKey)
      var originList = this.tableList
      var list = originList.filter(item => item.roleName.indexOf(this.searchKey) >= 0)
      this.tableList = list
    },
    handleAdd: function() {
      // this.resetFormFields()
      console.log(this.formData.parentCategoryId)
      this.dialogFormVisible = true
      // this.getForSelectList(0)
      // this.formData.parentCategoryId = -1
      this.isAddBtnClick = true
    },
    handleRefresh: function() {
      this.fetchList()
      this.$message.success('刷新成功！')
    },
    handleEnableOrDisable: function(item, index) {
      this.currentIndex = index
      updateCategoryStatus(item.id).then(res => {
        this.tableList.splice(index, 1, res.data)
      })
    },
    handleEdit: function(item, index) {
      this.currentIndex = index
      this.dialogFormVisible = true
      // this.getForSelectList(item.id)

      // 编辑的时候，给form赋值需要延后执行，否则重置表单将不生效
      this.$nextTick(() => {
        this.formData = Object.assign({}, item)
        // this.selectedCategory = this.formData.parentCategoryId
      })
      this.isAddBtnClick = false
    },
    // 分类删除
    handleDel: function(id, index) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteArticleCategory(id).then(res => {
          this.tableList.splice(index, 1)
          this.$message.success('删除成功!')
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 弹出框取消按钮点击事件
    handleFormCancel: function() {
      this.dialogFormVisible = false
      // this.$refs[formName].resetFields()
    },
    // 弹出框确定按钮点击事件
    handleFormConfirm: function() {
      this.dialogFormVisible = false
      var temp = Object.assign({}, this.formData)
      var data = {
        categoryName: temp.categoryName,
        description: temp.description,
        remarks: temp.remarks,
        parentCategoryId: temp.parentCategoryId.toString()
      }
      console.log(data)
      // this.$refs[formName].resetFields()
      if (this.isAddBtnClick) {
        addArticleCategory(data).then(res => {
          console.log(res)
          console.log(this.tableList)
          this.tableList.push(res.data)
          this.$message.success('增加成功！')
        })
      } else {
        updateArticleCategory(temp.id, data).then(res => {
          this.tableList.splice(this.currentIndex, 1, res.data)
          this.$message.success('修改成功！')
        })
      }
    },
    // 对话窗口关闭时 重置表单项
    handleDialogClose: function() {
      this.resetFormFields()
    },
    resetFormFields() {
      var formDialog = this.$refs.formDialog
      if (formDialog) {
        formDialog.resetFields()
      }
    },
    selectChanged: function() {
      var selected = this.formData.parentCategoryId
      console.log(selected)
    },
    handlePageSizeChange: function(pageSize) {
      // 这里并不会直接调用get方法，而是通过改变绑定的页面大小，来触发翻页事件
      this.pageData.pageIndex = 1
      this.pageData.pageSize = pageSize
      this.getArticleCategoryList()
    },
    handlePageIndexChange: function(pageIndex) {
      this.pageData.pageIndex = pageIndex
      this.getArticleCategoryList()
    },
    getArticleCategoryList: function() {
      getArticleCategory(this.pageData.pageIndex, this.pageData.pageSize).then(res => {
        console.log(res)
        this.pageData.totalItem = res.data.totalItem
        this.pageData.totalPage = res.data.totalPage
        this.tableList = res.data.list
      })
    },
    // 用于获取选择下拉列表的值
    getForSelectList(id) {
      getCategoryForSelect(id).then(res => {
        this.selectCategoryList = res.data
      })
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
